<template>
	<view class="content">

		<!-- 地址信息 -->
		<view class="address-section" @click="selectAddress">
			<u-icon name="map-fill" size="30" color="#ff4757" style="margin-right: 10rpx;"></u-icon>
			<text class="address-text">{{ currentAddress }}</text>
			<u-icon name="arrow-down" size="24" color="#666"></u-icon>
		</view>

		<!-- 临时退出按钮 -->
		<view class="logout-btn" @click="handleLogout"
			style="background: red; color: white; padding: 20rpx; margin: 20rpx; text-align: center; border-radius: 10rpx;">
			退出登录（测试）
		</view>

		<!-- 搜索框 -->
		<view class="search-section">
			<u-search placeholder="搜索商家、商品名称" :showAction="false" height="80rpx" inputAlign="center"
				v-model="searchKeyword" @search="onSearch">
			</u-search>
		</view>

		<!-- 轮播图 -->
		<view class="swiper-section">
			<u-swiper :list="bannerList" height="200" radius="15" indicator="true" indicatorMode="dot">
			</u-swiper>
		</view>

		<!-- 商品推荐 -->
		<view class="recommend-section">
			<u-text text="商品推荐" bold="true" color="#1976d2" size="20" margin="15px"></u-text>
			<scroll-view class="product-scroll" scroll-x="true">
				<view class="product-list">
					<view class="product-item" v-for="(product, index) in recommendProducts" :key="index">
						<view class="product-image-container">
							<u--image :src="product.image" width="100%" height="280rpx" radius="8px"
								:showLoading="true">
							</u--image>
							<!-- 特价标签 -->
							<view class="discount-tag" v-if="product.discount">
								<text class="discount-text">{{ product.discount }}</text>
							</view>
						</view>
						<view class="product-info">
							<view class="product-title-row">
								<text class="product-name">{{ product.name }}</text>
								<text class="sales-count">月售：{{ product.monthlySales }}</text>
							</view>
							<view class="product-bottom">
								<text class="product-price">¥{{ product.price }}</text>
								<view class="buy-btn" @click="goToProductDetail(product)">
									<text class="buy-text">立即购买>></text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 推荐商家 -->
		<view class="merchant-section">
			<u-text text="推荐商家" bold="true" color="#1976d2" size="20" margin="15px"></u-text>
			<view class="merchant-item" v-for="(merchant, index) in recommendMerchants" :key="index"
				@click="goToMerchant(merchant)">
				<u--image :src="merchant.image" width="120rpx" height="120rpx" radius="8px" :showLoading="true">
				</u--image>
				<view class="merchant-info">
					<text class="merchant-name">{{ merchant.name }}</text>
					<view class="merchant-rating">
						<u-icon name="star-fill" color="orange" size="24"></u-icon>
						<text class="rating-text">{{ merchant.rating }}</text>
						<text class="sales-text">月售：{{ merchant.monthlySales }}</text>
					</view>
					<view class="merchant-delivery">
						<text class="delivery-info">起送¥{{ merchant.minOrder }} 配送{{ merchant.deliveryFee }}</text>
						<text class="delivery-time">{{ merchant.deliveryTime }} {{ merchant.distance }}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		logout
	} from '@/utils/auth.js'
	import {
		get
	} from '@/utils/request'

	export default {
		data() {
			return {
				searchKeyword: '',
				currentAddress: '麓谷小镇岳麓大道尖山路口北300米',
				bannerList: [
					"/static/swiper/3.png",
					"/static/swiper/2.png",
					"/static/swiper/1.png"
				],
				recommendProducts: [{
						id: 1,
						name: '打印（可免费送...',
						price: '0.01',
						monthlySales: 1,
						image: '/static/recommendGood/2.png'
					},
					{
						id: 2,
						name: '藤席',
						price: '22',
						monthlySales: 0,
						image: '/static/recommendGood/3.png',
						discount: '柔韧易折'
					}
				],
				recommendMerchants: []
			}
		},
		onLoad() {
			this.loadData();
			this.fetchMerchants();
		},
		methods: {
			//退出登录
			handleLogout() {
				logout();
			},

			// 加载数据
			async loadData() {
				// 这里可以调用API获取数据
				// this.loadRecommendProducts();
				// this.loadRecommendMerchants();
			},

			// 选择地址
			selectAddress() {
				uni.navigateTo({
					url: '/pages/address/address'
				});
			},

			// 搜索
			onSearch(keyword) {
				console.log('搜索关键词:', keyword);
				// 执行搜索逻辑
			},

			// 跳转到商品详情
			goToProductDetail(product) {
				uni.navigateTo({
					url: `/pages/goodDetail/goodDetail?id=${product.id}`
				});
			},

			// 跳转到商家页面
			goToMerchant(merchant) {
			  const id = merchant?.id ?? merchant?.shopId
			  if (!id) {
			    uni.showToast({ icon: 'none', title: '缺少商家ID' })
			    return
			  }
			  uni.navigateTo({
			    url: `/pages/menu/menu?id=${encodeURIComponent(id)}`
			  })
			},

			// 加载推荐商品
			async loadRecommendProducts() {
				try {
					// 模拟API调用
					// const response = await this.$http.get('/api/products/recommend');
					// this.recommendProducts = response.data;
				} catch (error) {
					console.error('加载推荐商品失败:', error);
				}
			},

			// 加载推荐商家
			async fetchMerchants() {
				try {
					const res = await get('/order/shop/list', {
						pageNum: 1,
						pageSize: 6,
						shopStatus: 1,
					})
					console.log(res.rows)
					const rows = Array.isArray(res?.rows) ? res.rows : (Array.isArray(res) ? res : [])

					const FILE_BASE = (process.env.VUE_APP_FILE_BASE || process.env.VUE_APP_BASE_API || '').replace(
						/\/$/, '')
					const normalize = (u) => {
						if (!u) return ''
						if (/^https?:\/\//i.test(u)) return u
						return `${FILE_BASE}${u.startsWith('/') ? '' : '/'}${u}`
					}

					this.recommendMerchants = rows.slice(0, 6).map(s => ({
						id: s.shopId,
						image: normalize(s.shopAvatar || s.shopPhoto),
						name: s.shopName,
						rating: s.rating || '4.8',
						monthlySales: s.monthlySales ?? 0,
						minOrder: s.minOrder ?? 0,
						deliveryFee: s.deliveryFee ?? 0,
						deliveryTime: s.deliveryTime || '30分钟',
						distance: s.distance || ''
					}))
				} catch (e) {
					uni.showToast({
						icon: 'none',
						title: '商家加载失败'
					})
					console.error(e)
				}
			},
		}
	}
</script>

<style scoped>
	.content {
		background-color: #f8f9fa;
		min-height: 100vh;
	}

	/* 头部样式 */
	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #fff;
	}

	.app-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	.header-icons {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.icon {
		font-size: 28rpx;
		color: #666;
	}

	.target-icon {
		width: 50rpx;
		height: 50rpx;
		border-radius: 50%;
		border: 3rpx solid #333;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color: #333;
	}

	/* 地址样式 */
	.address-section {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #eee;
	}

	.address-text {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		margin: 0 10rpx;
	}

	/* 搜索框样式 */
	.search-section {
		padding: 20rpx 30rpx;
		background-color: #fff;
	}

	/* 轮播图样式 */
	.swiper-section {
		margin: 20rpx;
	}

	/* 商品推荐样式 */
	.recommend-section {
		margin-bottom: 30rpx;
	}

	.product-scroll {
		white-space: nowrap;
		padding: 0 20rpx;
	}

	.product-list {
		display: flex;
		gap: 20rpx;
	}

	.product-item {
		width: 350rpx;
		background-color: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		flex-shrink: 0;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.product-image-container {
		position: relative;
		height: 280rpx;
	}

	.discount-tag {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
		background-color: #ff4757;
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
	}

	.discount-text {
		color: #fff;
		font-size: 20rpx;
	}

	.product-info {
		padding: 20rpx;
	}

	.product-title-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 15rpx;
	}

	.product-name {
		font-size: 26rpx;
		color: #333;
		flex: 1;
	}

	.sales-count {
		font-size: 22rpx;
		color: #666;
	}

	.product-bottom {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.product-price {
		font-size: 32rpx;
		font-weight: bold;
		color: #ff4757;
	}

	.buy-btn {
		background-color: transparent;
	}

	.buy-text {
		font-size: 24rpx;
		color: #1976d2;
	}

	/* 推荐商家样式 */
	.merchant-section {
		padding: 0 20rpx;
	}

	.merchant-item {
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.merchant-info {
		flex: 1;
		margin-left: 20rpx;
	}

	.merchant-name {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 15rpx;
	}

	.merchant-rating {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
	}

	.rating-text {
		font-size: 24rpx;
		color: #ff9500;
		margin-left: 8rpx;
	}

	.sales-text {
		font-size: 24rpx;
		color: #666;
		margin-left: 30rpx;
	}

	.merchant-delivery {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.delivery-info,
	.delivery-time {
		font-size: 24rpx;
		color: #666;
	}
</style>